package Leo.controller;

import Leo.entity.param.Socialinfo;
import Leo.security.SystemProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class RootController {

    @Autowired
    ProviderSignInUtils providerSignInUtils; //spring social 获取qq(provider)的基本信息

    @Autowired
    SystemProperties systemProperties;

    RequestCache requestCache = new HttpSessionRequestCache(); //springboot的工具，用于缓存请求

    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); //springboot的工具，用于实现请求跳转

    Logger log =LoggerFactory.getLogger(RootController.class);

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(Long userId){
        return "test";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/signup")
    public String signup(){
        return "signup";
    }

    @RequestMapping("/errorpage")
    public String loginError(){
        return "errorpage";
    }

    @RequestMapping("/success")
    public String registerSuccess(){
        return "success";
    }

    @RequestMapping("/oauthRedirect")
    public String oauthRedirect(){
        return "oauthRedirect";
    }

    /**
     * 获取qq的Social信息，为了方便，在这里写逻辑，理论上应该在service里面写的
     * 在注册页面，前端调用这个方法，就可以获取到qq的信息了
     * @return
     */
    @RequestMapping("/socialinfo")
    public Socialinfo getSocialinfo(HttpServletRequest request){
        Socialinfo socialinfo = new Socialinfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        ConnectionKey key = connection.getKey();
        socialinfo.setProviderId(key.getProviderId());
        socialinfo.setProviderUserId(key.getProviderUserId());
        socialinfo.setNickName(connection.getDisplayName());
        socialinfo.setHeaderImg(connection.getImageUrl());
        return socialinfo;
    }

    @RequestMapping("/register")
    public String register(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String userId = request.getParameter("userId");
        //根据自身的业务逻辑获得userid
        userId = (System.currentTimeMillis() + "").substring(8);
        //写入UserConnection
        providerSignInUtils.doPostSignUp(userId,new ServletWebRequest(request));
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(savedRequest != null){
            //引发请求的url
            String redirectUrl = savedRequest.getRedirectUrl();
            log.debug("注册后跳转到：" + redirectUrl);
            log.debug("request的contextPath为：" + request.getContextPath());
//            response.sendRedirect("/spring/errorpage");

        }else{
//            response.sendRedirect("/spring/success");
        }
        return "index";
    }

    /**
     * 需要身份认证时，跳转到这里来
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authrequire")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)//设置状态码为未授权401
    public HttpServletResponse authenticationRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //保存引发身份认证跳转的请求
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(savedRequest != null){
            //引发请求的url
            String redirectUrl = savedRequest.getRedirectUrl();
            log.debug("引发跳转的请求是：" + redirectUrl);
//            redirectStrategy.sendRedirect(request,response,"/login"); //此处直接跳转，就不走下面的代码了
//            if(StringUtils.endsWithIgnoreCase(redirectUrl,".html")){ //如果是.html结尾的网页引发的跳转
//                redirectStrategy.sendRedirect(request,response,"/login"); //此处直接跳转，就不走下面的代码了
//            }
        }
        response.sendRedirect("/spring/login");
//        return new SimpleResponse("此请求需要身份认证");
        return response;
    }
}
